package com.zhkj.crawl.rank.ext;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

public class TraditionalMedicine {
    private static final String UA = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36";
    private static final JSONObject category = new JSONObject();

    public static void main(String[] args) throws IOException {
        getAll();
    }

    private static void getAll(){
        for (int i = 65; i < 91; i++) {
            get((char) i);
        }

        System.out.println(category);
    }

    private static void get(char z) {
        String s = String.valueOf(z);
        String url = "http://yaocai.zyctd.com/Ajax/AjaxHandle.ashx?CommandName=common/MCodexService/GetCodexNameByLetter";
        String body = HttpRequest.post(url)
                .header(Header.USER_AGENT, UA)
                .header(Header.CONTENT_TYPE, ContentType.FORM_URLENCODED.toString())
                .form("Data", String.format("{\"letter\":\"%s\",\"url\":\"\"}", s))
                .execute().body();

        JSONObject json = JSON.parseObject(body);
        JSONArray data = json.getJSONArray("Data");

        System.out.printf("%s下有%s条数据：\n", s, data.size());
        for (Object datum : data) {
            JSONObject item = (JSONObject) datum;
            item.remove("URL");
            item.remove("_MName");

            JSONArray arr = (JSONArray) category.getOrDefault(s, new JSONArray());
            arr.add(item);

            System.out.println(item);
            category.putIfAbsent(s, arr);
        }
        System.out.println("");
    }

}
